package Lab6;

import lombok.Data;

import java.util.Scanner;
import java.util.regex.Pattern;

@Data
public class ParityBitAdder {
    private String bitString;

    public ParityBitAdder(String pattern) {
        bitCheck(pattern);
    }

    private void bitCheck(String pattern) {
        boolean result = Pattern.matches("[0|1]{7}\s[0|1]", pattern);
        Scanner scanner = new Scanner(System.in);
        String input;
        while (!result) {
            System.out.println("Please input the right type!");
            input = scanner.nextLine();
            result = Pattern.matches("[0|1]{7}\s[0|1]", input);
            if (result) {
                setBitString(input);
                scanner.close();
            }
        }
    }

    public void calculateParity() {
        String bit = bitString.split("\s")[0];
        String index = bitString.split("\s")[1];
        int num = Integer.valueOf(bit, 2);
        int tol = 0;
        for (int i = 0; i < 7; i++) {
            tol = (num & 0x01) == 1 ? tol + 1 : tol;
            num >>= 1;
        }
        if (index.equals("0")) {
            System.out.printf("Adding even parity to ‘%s’ results in the binary pattern ‘%c%s’\n", bit, tol % 2 == 0 ? '0' : '1', bit);
        } else {
            System.out.printf("Adding odd parity to ‘%s’ results in the binary pattern ‘%c%s’\n", bit, tol % 2 == 1 ? '0' : '1', bit);
        }

    }
}
